package com.sora.sora.common.exception;

import com.sora.sora.common.constant.ResultCode;
import com.sora.sora.common.model.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class ExceptionControllerAdvice {

    @ExceptionHandler(ApiException.class)
    public ResultVO<String> apiExceptionHandler(ApiException e) {
        log.error(e.getMsg(), e.toString());
        return new ResultVO<>(e.getResultCode(), e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e.toString());
        ObjectError error = e.getBindingResult().getAllErrors().get(0);
        return new ResultVO<>(ResultCode.VALIDATE_FAILED, error.getDefaultMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public String usernameNotFoundException(UsernameNotFoundException e) {
        log.error(e.getMessage(), e.toString());
        return e.getMessage();
    }
}
